<?php

/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-20
 * 版    本：1.0.0
 * 功能说明：用户控制器。
 *
 * */

namespace Qwadmin\Controller;

//use Common\Controller\openerp;

class OrderController extends ComController {
    /*
     * 商品列表
     */

    function __construct() {
        parent::__construct();
    }

    public function index() {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('Order');
        $sh['ref'] = I('get.ref');
        $sh['buyer_name'] = I('get.buyer_name');
        $where = array();

        if( I('get.start_time') && I('get.end_time') ) {
            $where['date_order'] = array('between' , array(I('get.start_time') , date('Y-m-d' , strtotime( I('get.end_time') . ' +1 day'))));
        } else if( I('get.start_time') ) {
            $where['date_order'] = array( 'EGT' ,  I('get.start_time') );
        } else if( I('get.end_time')) {
            $where['date_order'] = array( 'ELT' ,  date('Y-m-d' , strtotime( I('get.end_time') . ' +1 day') ) );
        }

        if ($sh['buyer_name'] && !empty($sh['buyer_name'])) {
            $where['buyer_name'] = array('like', $sh['buyer_name']);
        }
        if ($sh['ref'] && !empty($sh['ref'])) {
            $where['ref'] = array('eq', $sh['ref']);
        }
        
        if ($_GET['distribution_customer_id'] && !empty($_GET['distribution_customer_id'])) {
            $where['distribution_customer_id'] = $_GET['distribution_customer_id'];
        }
        
        $pagesize = 20; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
        $count = $m->where($where)->count();
        $list = $m->where($where)->limit($offset . ',' . $pagesize)->order("id desc")->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $channel_codelist = $m->field("channel_code")->group('channel_code')->cache(200)->select();
        $trade_patternlist = $m->field("trade_pattern")->group('trade_pattern')->cache(204)->select();
        $ebpCodelist = $m->field("ebpCode")->group('ebpCode')->cache(204)->select();
        foreach( $list as $key => $value ) {
            $list[$key]['distribution_name'] = M('customer')->where(array('id' => $value['distribution_customer_id']))->getField( 'shop_name' );
        }
        $this->assign('list', $list);
        $this->assign('channel_codelist', $channel_codelist);
        $this->assign('trade_patternlist', $trade_patternlist);
        $this->assign('ebpCodelist', $ebpCodelist);
        $this->assign('page', $page);

        // ========== 以下统计操作 ==========//
        $this->assign('order_total' , $m->where($where)->count()); //订单总数
        $this->assign('order_total_price' , $m->where($where)->sum('amount_total')); //订单总金额
        $this->assign('order_not_pay_price' , $m->where(array_merge(($where ? $where : array()),array('state' => 0)))->sum('amount_total')); //未付款总金额
        $this->assign('order_no_pay_total' , $m->where(array_merge(($where ? $where : array()),array('state' => 0)))->count()); //订单未付款总数

        $this->display();
    }

    /***
     * 
     * 订单详情
     */
    function detail(){
        $id = I("get.id", "0");
        if (!$id) {
            $this->error("参数错误", U("index"));
        }
        $m = D("order");
        $res = $m->relation(true)->where(array('id' => $id))->find();
        $send_express = 0;
        if ($res && isset($res['order_line'])) {
            $res['orderAmount'] = 0;
            foreach ($res['order_line'] as $key => $value) {
                if (!$value['express_name']) {
                    $send_express = 1;
                }
                $res['order_line'][$key]['earn13'] = M('goods')->where(array('sku' => $value['sku']))->getField('earn13');
                $res['orderAmount']+= $res['order_line'][$key]['supply_price'] * $res['order_line'][$key]['num'];
            }
        }
        //分供应商组合数据
        foreach( $res['order_line'] as $key => $value ) {
            $res['order_customer_line'][$value['supply_customer_id']]['list'][] = $value;
            $res['order_customer_line'][$value['supply_customer_id']]['supply_name'] = M('customer')->where(array('id' => $value['supply_customer_id']))->getField('shop_name');
            $res['order_customer_line'][$value['supply_customer_id']]['price_total'] += $value['supply_price'] * $value['num'] + $value['fee'];
            $res['order_customer_line'][$value['supply_customer_id']]['goods_total'] += 1;
            $res['order_customer_line'][$value['supply_customer_id']]['pay_status'] = $value['pay_status'];
            $res['order_customer_line'][$value['supply_customer_id']]['express_name'] = $value['express_name'];
            $res['order_customer_line'][$value['supply_customer_id']]['express_no'] = $value['express_no'];
            $res['order_customer_line'][$value['supply_customer_id']]['send_time'] = $value['send_time'];
            $res['order_customer_line'][$value['supply_customer_id']]['payment_no'] = $value['payment_no'];
            $res['order_customer_line'][$value['supply_customer_id']]['pay_type'] = $value['pay_type'];
            $res['order_customer_line'][$value['supply_customer_id']]['pay_money'] = $value['pay_money'];
            $res['order_customer_line'][$value['supply_customer_id']]['pay_time'] = $value['pay_time'];
            $res['order_customer_line'][$value['supply_customer_id']]['ref'] = $value['ref'];
            $res['order_customer_line'][$value['supply_customer_id']]['fee'] += $value['fee'];
        }
        unset( $res['order_line'] );
        $send_types = explode('|', C('SEND_TYPES'));
        //获得来源平台
        $this->assign('platform_name', M('customer_platform_bind')->where(array('id' => $res['platform_id']))->getField('name'));
        $this->assign('send_types', $send_types);
        $this->assign("val", $res);
        $this->assign('type', I('get.type'));
        $this->assign('send_express', $send_express);
        $this->display();
    }
    /*
     * 商品添加
     */

    public function add() {

        $tradeList = M("Trade")->group('code')->select();
        foreach($tradeList as $key=>$tradeLis){
            $tradeList[$key]['code']=  strtolower($tradeLis['code']);
        }
//        echo "<pre>";print_r($tradeList);
        
        
        
        $channel_code=M("customer")->field("shop_name as name,code")->group("code")->select();
        $this->assign('tradeList', $tradeList);
        $this->assign('channel_code', $channel_code);
        $this->assign('paymentList', array('pcupacp',"alipay",'weixin',"cash"));

        $this->display('form');
    }

    public function update() {
        $m = M('goods');
        $id = I('post.id', '', 'intval');
        $data = I('post.arr');
        $pic_thumb = I('post.pic_thumb', '', 'strip_tags');

        $data['pic_thumb'] = $pic_thumb ? $pic_thumb : '';
        if ($data['info_keywords']) {
            $data['info_keywords'] = json_encode(array_unique(explode("、", $data['info_keywords'])));
        }

        if ($id) {
            $m->data($data)->where("id='{$id}'")->save();
            addlog('编辑商品，ID：' . $id);
        } else {
            $m->data($data)->add();
            addlog('新增商品，名称：' . $data['name']);
        }

        $this->success('操作成功！', U('index'));
    }

    /*
     * 商品编辑
     */

    public function edit($id = 0) {
        $id = intval($id);

        $m = M('goods');
        $goods = $m->where("id='$id'")->find();
        if (!$goods) {
            $this->error('参数错误！');
        }
        $goods['info_keywords'] = implode('、', json_decode($goods['info_keywords']));
        $goods_brand = M('Goods_brand')->field('id,name')->select();
        $goods_types = M('Goods_type')->field('id,name,pid')->select();
        $country = M('country')->where(array('enabled' => 'true'))->field('country_id,Chinese_name')->select();

        $tradeList = M("Trade")->group('code')->select();
        $tree = new \Tree\Tree(M('goods_type')->field('id,pid,name')->select());
        $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;|', '&nbsp;&nbsp;&nbsp;&nbsp;|------------', '&nbsp;&nbsp;&nbsp;&nbsp;|-');
        $this->assign('select_option_list', $tree->get_tree(0, '<option value=\$id \$selected>\$spacer\$name</option>'));
        $this->assign('tradeList', $tradeList);
        $this->assign('goods_brand', $goods_brand);

        $this->assign('country', $country);
        $this->assign('goods', $goods);
        $this->display('form');
    }

    public function del() {
        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;

        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $ids[$k] = intval($v);
            }
            if (!$ids) {
                $this->error('参数错误！');
                $uids = implode(',', $uids);
            }
        }

        $map['id'] = array('in', $ids);
        if (M('goods')->where($map)->delete()) {
            addlog('删除商品ID：' . $ids);
            $this->success('恭喜，商品删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }

    /*
     * 商品的批处理相关
     */

    function goodsBath() {
        $ids = I("post.ids");
        $siteids = I("post.siteids");
        $storeids = I("post.storeids", 0);
        $optype = I("post.optype", ADD_NEW);
//        var_dump($optype);die;
        $jumpUrl = $_SERVER['HTTP_REFERER'];
        if (empty($ids) || !$ids) {
            $this->error("商品为空，请选择要操作的商品");
        }
        if (empty($siteids) || !$siteids) {
            $this->error("站点为空，请选择要操作的站点");
        }
//        if (empty($storeids) || !$storeids) {
//            $this->error("店铺为空，请选择要操作的店铺");
//        }

        $data = array();
        foreach ($ids as $key => $goods_id) {
            foreach ($siteids as $sk => $svalue) {
                $tempdata['goods_id'] = $goods_id;
                $tempdata['site_id'] = $svalue;
                $tempdata['op'] = $optype;
                $tempdata['uid'] = $this->USER['uid'];
                $tempdata['store_id'] = $storeids;
                $tempdata['optime'] = time();
                $data[] = $tempdata;
            }
        }
//        var_dump($data);die;
        $opModel = M("Goods_op");
        $opModel->startTrans();
        foreach ($data as $goodsdata) {
            $where['goods_id'] = $goodsdata['goods_id'];
            $where['site_id'] = $goodsdata['site_id'];
            $where['op'] = $goodsdata['op'];
//            $where['store_id'] = $goodsdata['store_id'];
            $hasid = $opModel->where($where)->getField("id");
            if ($hasid) {
                $updata = $goodsdata;
                $updata['rsp'] = '';
                $flag = $opModel->where(array("id" => $hasid))->save($updata);
            } else {
                $flag = $opModel->add($goodsdata);
            }

            if (!$flag) {
                $opModel->rollback();
                $this->error("操作失败，请重试", $jumpUrl);
            }
        }
        $opModel->commit();
        $this->success("操作成功", $jumpUrl);
    }

    /**
     * 同步ERP
     */
    public function erpSync() {
        $id = I('get.id') ? I('get.id') : $this->error('参数错误！');
        if( !M('order')->where("`id` = {$id} AND `erp_order_sync` IN(0,1)")->find() ) {
            $this->error( '没有需要同步的订单' );
        }
        if( D('ErpApi')->erpOrderSyn( $id ) === false ) {
            $this->error( '订单同步失败' );
        } else {
            $this->success( '订单同步成功' );
        }
    }

    /**
     * 清关
     */
    public function clearance(){
        $id = I('get.id') ? I('get.id') : $this->error('参数错误！');
        if( !M('order')->where("`id` = {$id} AND `wx_order_sync` IN(0,1)")->find() ) {
            $this->error( '没有需要清关的订单' );
        }
        if( D('ErpApi')->clearance( $id ) === false ) {
            $this->error( '订单清关失败' );
        } else {
            $this->success( '订单清关成功' );
        }
    }

    /**
     * 数据统计
     */
    public function Count(){
        $where = array();
        //渠道
        if( I('get.channel_code') ) {
            $where['o.channel_code'] = I('get.channel_code');
        }
        //贸易模式
        if( I('get.trade_pattern') ) {
            $where['o.trade_pattern'] = I('get.trade_pattern');
        }
        //状态
        if( I('get.status') ) {
            switch( I('get.status') ) {
                case 1 : //未支付
                    $where['o.state'] = 0;
                break;
                case 2 : //已支付
                    $where['o.state'] = 1;
                break;
                case 3 : //已退款
                    $where['o.state'] = 7;
                break;
            }
        }

        $customer = M('customer')->select();

        //订单时间
        switch( I('get.type') ) {
            case 2 : //日报
                $day = ceil( (strtotime( I('get.end_time') ) - strtotime( I('get.start_time') ) ) / 86400 );
                $all_data = array();
                foreach( $customer as $key => $value ) {
                    $count_data = array();
                    for( $i=1; $i<=$day; $i++ ) {
                        $date_time = date('Y-m-d' , strtotime( I('get.start_time')." +{$i} day"));
                        $where['o.date_order'] = array('between' , array($date_time . " 00:00:00" , $date_time . " 23:59:59"));
                        $count_data['total_num'][] = "'{$date_time}'";
                        $total_price = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')
                                                 ->where($where)->getField('SUM(payamount)');
                        $count_data['total_data'][] = $total_price ? $total_price : 0;
                    }
                }
                $this->assign('title' , I('get.start_time').'到'.I('get.end_time').'订单走向图' );
            break;
            case 3 : //周报
                for( $i = I('get.start_time'); $i<=I('get.end_time'); $i++ ) {
                    $days = 7 * $i;
                    $date_time = date('Y-m-d' , strtotime( date('Y') . "-01-01 +{$days} day"));
                    $where['o.date_order'] = array('between' , array($date_time . " 00:00:00" , $date_time . " 23:59:59"));
                    $count_data['total_num'][] = "'". $this->getChinaStr( $i ) ."'";
                    $total_price = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')
                                             ->where($where)->getField('SUM(payamount)');
                    $count_data['total_data'][] = $total_price ? $total_price : 0;
                }
                $this->assign('title' , $this->getChinaStr( I('get.start_time') ).'到'.$this->getChinaStr( I('get.end_time') ).'订单走向图' );
            break;
            case 4 : //月报
                $year = I('get.start_time')?I('get.start_time'):date('Y');
                for( $i=1; $i<=12; $i++ ) {
                    $where['o.date_order'] = array('between' , array($year . "-{$i}-01 00:00:00" , $year . "-{$i}-31 23:59:59"));
                    $count_data['total_num'][] = "'{$i}月'";
                    $total_price = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')
                                             ->where($where)->getField('SUM(payamount)');
                    $count_data['total_data'][] = $total_price ? $total_price : 0;
                }
                $this->assign('title' , $year.'年订单走向图' );
            break;
            case 5 : //年报
                $year = date('Y');
                $count_data = array();
                for( $i = 2014; $i<= $year; $i++ ) {
                    $where['o.date_order'] = array('between' , array($i . "-01-01 00:00:00" , $i . "-12-31 23:59:59"));
                    $count_data['total_num'][] = "'{$i}年'";
                    $total_price = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')
                                             ->where($where)->getField('SUM(payamount)');
                    $count_data['total_data'][] = $total_price ? $total_price : 0;
                }
                $this->assign('title' , '2014年-'.$year.'年订单走向图' );
            break;
            default : 
                $date_time = I('get.start_time') ? I('get.start_time') : "2016-12-22";//date('Y-m-d');
                $count_data = array();
                for( $i = 0; $i<=23; $i++ ) {
                    $where['o.date_order'] = array('between' , array( $date_time . " {$i}:00:00" , $date_time . " {$i}:59:59" ));
                    $count_data['total_num'][] = "'{$i}时'";
                    $total_price = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')
                                             ->where($where)->getField('SUM(payamount)');
                    $count_data['total_data'][] = $total_price ? $total_price : 0;
                }
                $this->assign('title' , $date_time.'订单走向图' );
            break;
        }
        $count_data['total_num'] = implode(',' , $count_data['total_num']);
        $count_data['total_data'] = implode(',' , $count_data['total_data']);

        //获得渠道
        $this->assign( 'info' , $count_data );

        $week = array();
        for($i=1;$i<=52;$i++) {
            $week[] = array('title' => $this->getChinaStr($i) , 'id' => $i);
        }

        $this->assign('w_list'  , $week );
        $this->display();
    }

    private function getChinaStr(  $data ) {
        $data = (string)$data;
        $numbers = array('十','一','二','三','四','五','六','七','八','九');
        $length = strlen( $data );
        $str = '';
        $str.= $length > 1 ? ( $data == 10 ? '十' : ( $data[0] == 1 ? '十' . $numbers[$data[1]] : ($data[1] > 0 ? $numbers[$data[0]] . '十' . $numbers[$data[1]] : $numbers[$data[0]] . '十' )) ) : $numbers[$data];
        return '第'.$str.'周';
    }


    //获得贸易模式列表
    public function tradeList() {
        $data = I('get.id') ? I('get.id') : exit("");
        if( $list = M('trade')->where(array('site_id' => $data))->select()) {
            exit(json_encode( $list ) );
        }
        exit( '' );
    }

}
